<template>
  <div class="search-app-container">
    <!-- 顶部搜索栏 -->
    <header class="search-header">
      <div class="search-input-container">
        <el-input
          v-model="searchQuery"
          placeholder="请输入商家名称"
          clearable
          @keyup.enter="handleSearch"
          @clear="clearSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </header>

    <!-- 主要内容区域 -->
    <main class="search-main-content">
      <!-- 初始提示 -->
      <div v-if="showSearchTips" class="search-tips">
        <el-icon><Search /></el-icon>
        <p>输入商家名称进行搜索</p>
      </div>

      <!-- 加载状态 -->
      <div v-else-if="loading" class="search-loading">
        <el-icon class="loading-icon"><Loading /></el-icon>
        <span>正在搜索...</span>
      </div>

      <!-- 无结果提示 -->
      <div v-else-if="searchPerformed && merchants.length === 0" class="search-empty">
        <el-icon><Search /></el-icon>
        <p>没有找到匹配的商家</p>
      </div>

      <!-- 搜索结果列表 -->
      <div v-else class="search-results">
        <div 
          v-for="merchant in merchants" 
          :key="merchant.merchantId" 
          class="merchant-item"
          @click="goToShop(merchant)"
        >
          <div class="merchant-left">
            <img :src="getAvatarUrl(merchant.avatar_path)" class="merchant-image" alt="商家头像">
          </div>
          <div class="merchant-right">
            <div class="merchant-header">
              <h4 class="merchant-name ellipsis">{{ merchant.name }}</h4>
              <div class="merchant-tags">
                <el-tag v-if="merchant.distance <= 10" size="small" type="success">附近</el-tag>
                <el-tag v-else size="small" type="info">较远</el-tag>
              </div>
            </div>
            
            <div class="merchant-description ellipsis" v-if="merchant.description">
              {{ merchant.description }}
            </div>
            
            <div class="merchant-address ellipsis">
              <el-icon><Location /></el-icon>
              <span>{{ merchant.address }}</span>
            </div>
            
            <div class="merchant-delivery">
              <div class="delivery-info">
                <span>¥{{ merchant.leastprice }}起送</span>
              </div>
              <div class="delivery-time">
                <span>{{ getDeliveryTime(merchant.distance) }}</span>
                <span class="divider">/</span>
                <span>{{ merchant.distance.toFixed(2) }}km</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 底部导航 -->
    <FooterGuide />
  </div>
</template>

<script setup>
import { ref, computed, onMounted ,watch} from 'vue';
import { useRouter } from 'vue-router';
import { useCookies } from 'vue3-cookies';
import { Search, Loading, Location } from '@element-plus/icons-vue';
import axios from 'axios';
import { API_BASE_URL } from '@/config';
import FooterGuide from '@/components/FooterGuide/FooterGuide.vue';
import defaultMerchantImage from '@/assets/default-merchant.jpg'; // 导入默认头像图片
const { cookies } = useCookies();
const router = useRouter();

const searchQuery = ref('');
const merchants = ref([]);
const loading = ref(false);
const searchPerformed = ref(false);

// 计算属性
const showSearchTips = computed(() => {
  return !searchQuery.value && !searchPerformed.value;
});

// 获取商家头像完整URL
const getAvatarUrl = (path) => {
  if (!path) return defaultMerchantImage;
  return `${import.meta.env.VITE_API_BASE_URL}${path}`;
};

// 根据距离估算配送时间
const getDeliveryTime = (distance) => {
  if (distance <= 1) return '20-30分钟';
  if (distance <= 3) return '30-40分钟';
  if (distance <= 5) return '40-50分钟';
  return '50-60分钟';
};

// 搜索商家
const handleSearch = async () => {
  if (!searchQuery.value.trim()) return;

  loading.value = true;
  searchPerformed.value = true;

  try {
    // 从cookie获取经纬度
    const latitude = parseFloat(cookies.get('latitude') || 39.915);
    const longitude = parseFloat(cookies.get('longitude') || 116.404);

    const response = await axios.get(`${API_BASE_URL}/merchant/search`, {
      params: {
        input: searchQuery.value.trim(),
        longitude: longitude,
        latitude: latitude
      }
    });

    // 处理返回数据
    if (response.data === "未找到店铺") {
      merchants.value = [];
    } else {
      merchants.value = response.data;
      response.data.forEach((merchant, index) => {
        console.log(`商家 ${index + 1}:`, merchant);
      });
    }
  } catch (error) {
    console.error('搜索失败:', error);
    merchants.value = [];
  } finally {
    loading.value = false;
  }
};

// 清空搜索
const clearSearch = () => {
  searchPerformed.value = false;
  merchants.value = [];
};

// 跳转到商家详情
const goToShop = (merchant) => {
  router.push({
    path: `/ShopDetail/${merchant.merchantId}`,
    query: {
      address: merchant.address,
      phone: merchant.merchantPhone,
      leastprice: merchant.leastPrice,
      description: merchant.description,
      name: merchant.name || '',
      avatar: merchant.avatarPath || '',
      distance: merchant.distance || 0
    }
  });
};

// 防抖搜索
let searchTimer = null;
watch(searchQuery, (newVal) => {
  if (searchTimer) clearTimeout(searchTimer);
  
  if (newVal.trim()) {
    searchTimer = setTimeout(() => {
      handleSearch();
    }, 500);
  } else {
    clearSearch();
  }
});
</script>

<style scoped>
/* 基础重置 */
.search-app-container {
  margin: 0;
  padding: 0;
  width: 100vw;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow-x: hidden;
}

/* 顶部搜索栏 */
.search-header {
  position: sticky;
  top: 0;
  z-index: 100;
  background-color: #02a774;
  padding: 12px 15px;
  width: 100%;
  box-sizing: border-box;
}

.search-input-container {
  width: 100%;
  max-width: 100%;
}

/* 主要内容区域 */
.search-main-content {
  flex: 1;
  width: 100%;
  padding: 15px;
  box-sizing: border-box;
  overflow-y: auto;
  margin-bottom: 50px;
}

/* 状态提示样式 */
.search-tips,
.search-loading,
.search-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: calc(100vh - 150px);
  color: #888;
}

.search-tips .el-icon,
.search-empty .el-icon {
  font-size: 50px;
  margin-bottom: 15px;
  color: #ccc;
}

.loading-icon {
  font-size: 40px;
  margin-bottom: 10px;
  animation: rotating 2s linear infinite;
}

/* 搜索结果列表 */
.search-results {
  padding-bottom: 60px;
}

.merchant-item {
  display: flex;
  padding: 12px;
  margin-bottom: 12px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  cursor: pointer;
}

.merchant-left {
  margin-right: 12px;
}

.merchant-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
}

.merchant-right {
  flex: 1;
  min-width: 0;
}

.merchant-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
}

.merchant-name {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.merchant-tags {
  margin-left: 8px;
}

.merchant-description {
  color: #666;
  font-size: 13px;
  margin-bottom: 6px;
}

.merchant-address {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 12px;
  margin-bottom: 6px;
}

.merchant-address .el-icon {
  margin-right: 4px;
  font-size: 14px;
}

.merchant-delivery {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
}

.delivery-info span {
  color: #ff5339;
}

.delivery-time .divider {
  margin: 0 4px;
}

/* 动画 */
@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 文本溢出处理 */
.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>